<?php
//+-----------------------------------------------------------
//| 人生是荒芜的旅行，冷暖自知，苦乐在心
//+-----------------------------------------------------------
//| Author:Janmas <janmas@126.com>
//+-----------------------------------------------------------
//| 
//+-----------------------------------------------------------


namespace app\admin\service;


use app\admin\exception\DataNotFoundException;
use app\admin\exception\LogicException;
use app\admin\exception\MethodException;
use app\admin\model\AdminModel;
use app\common\model\BaseModel;
use app\common\traits\Jump;
use app\common\validate\BaseValidate;
use think\Request;

/**
 * Class BaseService
 * @package app\admin\service
 * @property BaseModel $model
 * @property BaseValidate $validate
 * @method afterCreate(BaseModel $model,$data)
 * @method afterUpdate(BaseModel $model,$data)
 */
abstract class AdminService
{
    use Jump;

    protected $request;

    protected $model;

    protected $validate;

    public function __construct ( Request $request = null )
    {
        $this->request = $request;
        $this->init();
    }

    abstract protected function init ();

    /**
     * 获取当前模型
     * @return BaseModel
     */
    public function getModel ()
    {
        return $this->model;
    }

    /**
     * 获取当前验证器
     * @return BaseValidate
     */
    public function getValidate ()
    {
        return $this->validate;
    }

    /**
     * 增
     */
    public function create ()
    {
        if ( !$this->request->isPost() ) {
            throw new MethodException('请求方式错误');
        }

        $data = $this->request->post();
        $files = $this->request->file();

        foreach ($files??[] as $key=>$file){
            try{
                $data[$key] = \app\admin\model\FileManager::upload($file);
            }catch (\Exception $e){
                $data[$key] = $data[$key.'file'];
            }
            unset($data[$key.'file']);
        }

        //验证器在的话就调用验证器
        if ( !is_null($this->validate) ) {
            $this->validate->go($data , 'create');
        }

        if ( method_exists($this->model , 'setField') ) {
            $data = $this->model->setField($data);
        }

        if ( method_exists($this , 'afterCreate') ) {
            $this->model->startTrans();
            if ( $this->afterCreate($this->model->create($data),$data)) {
                $this->model->commit();
                return $this->success('操作成功:新增');
            }

            $this->model->rollback();
        } else {
            if ( $this->model->create($data) ) {
                return $this->success('操作成功:新增');
            }
        }

        throw new LogicException('添加失败:新增');
    }

    /**
     * 改
     * @param array $where
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function update ( $where = [] )
    {
        if ( !$this->request->isPost() ) {
            throw new MethodException('请求方式错误');
        }

        //三目区分
        $info = empty($where) ?
            $this->model->findOrEmpty($this->request->get('id/d' , 0)) :
            $this->model->where($where)->findOrEmpty();

        if ( $info->isEmpty() ) {
            throw new DataNotFoundException('指定条件的数据不存在');
        }

        $data = $this->request->post();

        $files = $this->request->file();
        foreach ($files??[] as $key=>$file){
            try{
                $data[$key] = \app\admin\model\FileManager::upload($file);
            }catch (\Exception $e){
                $data[$key] = $data[$key.'file'];
            }
            unset($data[$key.'file']);
        }

        if ( !is_null($this->validate) ) {
            $this->validate->go($data , 'update');
        }

        if ( method_exists($this->model , 'setField') ) {
            $data = $this->model->setField($data);
        }

        if(method_exists($this,'afterUpdate')){
            $this->model->startTrans();
            if(
                $info->allowField($this->model->getSubmitField())->data($data , true)->save()
                &&
                $this->afterUpdate($info,$data)
            ){
                $this->model->commit();
                return $this->success('操作成功:更新');
            }
	        $this->model->rollback();
        }else{
            if ( $info->data($data , true)->save() ) {
                return $this->success('操作成功:更新');
            }
        }

        throw new LogicException('操作失败:更新');
    }

    public function delete ()
    {
        if ( $this->request->isGet() ) {
            $ids[] = $this->request->get('id');
        }
        else {
            $ids = $this->request->post('ids');
        }

	    /**
	     * 删除前的操作妈的好像写model层也行
	     */
	    if(method_exists($this,'beforeDelete')){
		    $this->beforeDelete();
	    }

        if ( property_exists($this->model , 'deleteTime') ) {
            if ( $this->model->where('id' , 'in' , $ids)->update([ $this->model->getDeleteTime() => time() ]) ) {
                return $this->success('操作成功:删除');
            }
        }else {
            if ($this->model->delete($ids) ) {
                return $this->success('操作成功:删除');
            }
        }


        throw new LogicException('操作失败:删除');
    }

    public function destory ( $where = [] )
    {
        if ( empty($where) ) {
            $where = $this->request->has('ids' , 'post') ? $this->request->post('ids') : $this->request->get('id');
            $res   = $this->model->force()->delete($where);
        }
        else {
            $res = $this->model->force()->where($where)->delete();
        }

        if ( $res !== false ) {
            $this->success('操作成功:删除');
        }

        throw new LogicException('操作失败:删除');
    }

    /**
     * 根据id获取单条数据用于update渲染页面
     * @return array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getInfo(){
        $id = $this->request->get('id/d',0);
        return $this->model->find($id);

    }
    /**
     * 查数据表格需要的东西
     * @param array $where
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getTableList ( $where = [] )
    {
        $page  = $this->request->request('page/d' , 0);
        $limit = $this->request->request('limit/d' , 10);
        $list  = $this->model->where($where)->order('id asc')->page($page)->limit($limit)->select();
        return json([
            'code'  => 0 ,
            'data'  => $list ,
            'count' => $this->model->where($where)->count() ,
            'msg'   => ''
        ]);
    }

    /**
     * 动态form表单构建
     * @return string
     */
    public function getHtml():string
    {
        return '';
    }
}